﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using File_Manager.Models;
using System.Web.Routing;
using System.Web.Security;
using PagedList;
/*Envío de Correos*/
using System.Net;
using System.Net.Mail;
using System.Data;
using System.IO;
using System.Net.Mime;

namespace File_Manager.Controllers
{ 
    public class Post_CYTController : Controller
    {
        private CYTContext db = new CYTContext();

        //
        // GET: /Post_CYT/
        [Authorize(Roles = "Guest_C, Guest_H, Guest_I")]
        public ViewResult SearchIndexG(string SearchAsunto, string CurrentAsunto, string msn,
                                       int? SearchId, int? CurrentId, int? SearchStatus, int? page = 1)
        {
            ViewBag.postPending = (from m in db.Post_CYT
                                   where (m.userName == User.Identity.Name && m.idStatus == 1)
                                   select m.id).Count();

            var post_cyt = db.Post_CYT.Include(b => b.nUser_I).Include(b => b.nStatus);

            //Metodo GET Inicializar las variables con los valores de busqueda introducidos
            if (Request.HttpMethod == "GET")
            {
                ViewBag.msn = msn;
                SearchAsunto = CurrentAsunto;
                SearchId = CurrentId;
                ViewBag.SearchStatus = new SelectList(new[]
                {
                    new SelectListItem{ Value = "1", Text = "Pendiente" },
                    new SelectListItem{ Value = "2", Text = "Aprobado" },
                }, "Value", "Text");
            }
            else
            {
                page = 1;
            }

            ViewBag.CurrentAsunto = SearchAsunto;
            ViewBag.CurrentId = SearchId;

            ViewBag.SearchStatus = new SelectList(new[]
                {
                    new SelectListItem{ Value = "1", Text = "Pendiente" },
                    new SelectListItem{ Value = "2", Text = "Aprobado" },
                }, "Value", "Text", SearchStatus);

            ViewBag.CurrentStatus = SearchStatus;

            if (!String.IsNullOrEmpty(SearchAsunto))
            {
                post_cyt = post_cyt.Where(s => s.asunto.Contains(SearchAsunto));
            }

            if (SearchId != null)
            {
                post_cyt = post_cyt.Where(m => m.id == SearchId);
            }

            if (SearchStatus != null)
            {
                post_cyt = post_cyt.Where(m => m.idStatus == SearchStatus);
            }


            post_cyt = post_cyt.Where(m => m.userName == User.Identity.Name).OrderByDescending(m => m.id);

            int pageSize = 10;
            int pageIndex = (page ?? 1);

            return View(post_cyt.ToList().ToPagedList(pageIndex, pageSize));
        }

        //
        // GET: /Post_CYT/
        [Authorize(Roles = "Admin")]
        public ViewResult SearchIndexA(string SearchName, string CurrentName, string SearchLastname, string CurrentLastname,
                                       string SearchAsunto, string CurrentAsunto, string msn,
                                       int? SearchId, int? CurrentId, int? SearchStatus, int? page = 1)
        {

            var post_cyt = db.Post_CYT.Include(b => b.nUser_I).Include(b => b.nStatus);

            //Metodo GET Inicializar las variables con los valores de busqueda introducidos
            if (Request.HttpMethod == "GET")
            {
                ViewBag.msn = msn;
                SearchName = CurrentName;
                SearchLastname = CurrentLastname;
                SearchAsunto = CurrentAsunto;
                SearchId = CurrentId;
                ViewBag.SearchStatus = new SelectList(new[]
                {
                    new SelectListItem{ Value = "1", Text = "Pendiente" },
                    new SelectListItem{ Value = "2", Text = "Aprobado" },
                }, "Value", "Text");
            }
            else
            {
                page = 1;
            }


            ViewBag.CurrentName = SearchName;
            ViewBag.CurrentLastname = SearchLastname;
            ViewBag.CurrentAsunto = SearchAsunto;
            ViewBag.CurrentId = SearchId;

            ViewBag.SearchStatus = new SelectList(new[]
                {
                    new SelectListItem{ Value = "1", Text = "Pendiente" },
                    new SelectListItem{ Value = "2", Text = "Aprobado" },
                }, "Value", "Text", SearchStatus);

            ViewBag.CurrentStatus = SearchStatus;


            //Filtrado por los parametros en entrada capturado en al interfaz
            if (!String.IsNullOrEmpty(SearchName))
            {
                var User_I = from m in db.User_I
                             where m.name.Contains(SearchName)
                             select m.UserName;
                post_cyt = post_cyt.Where(s => User_I.Contains(s.userName));
            }

            if (!String.IsNullOrEmpty(SearchLastname))
            {
                var User_I = from m in db.User_I
                             where m.last_name.Contains(SearchLastname)
                             select m.UserName;
                post_cyt = post_cyt.Where(s => User_I.Contains(s.userName));
            }

            if (!String.IsNullOrEmpty(SearchAsunto))
            {
                post_cyt = post_cyt.Where(s => s.asunto.Contains(SearchAsunto));
            }

            if (SearchId != null)
            {
                post_cyt = post_cyt.Where(m => m.id == SearchId);
            }

            if (SearchStatus != null)
            {
                post_cyt = post_cyt.Where(m => m.idStatus == SearchStatus);
            }
            
            int pageSize = 10;
            int pageIndex = (page ?? 1);

            post_cyt = post_cyt.OrderBy(x => x.id);

            return View(post_cyt.ToList().ToPagedList(pageIndex, pageSize));
        }

        //
        // GET: /Post_CYT/Details/5
        [Authorize(Roles = "Guest_C, Guest_H, Guest_I")]
        public ViewResult Details(int id)
        {
            Post_CYT post_cyt = db.Post_CYT.Find(id);
            User_I userGuest= db.User_I.Find(post_cyt.userName);
            MembershipUser currentUser = Membership.GetUser(post_cyt.userName);

            ViewBag.nameGuest = userGuest.name;
            ViewBag.lastnameGuest = userGuest.last_name;
            ViewBag.mailGuest = currentUser.Email;

            return View(post_cyt);
        }

        //
        // GET: /Post_CYT/Details/5
        [Authorize(Roles = "Admin")]
        public ViewResult DetailsAdmin(int id)
        {
            Post_CYT post_cyt = db.Post_CYT.Find(id);
            User_I userGuest = db.User_I.Find(post_cyt.userName);
            MembershipUser currentUser = Membership.GetUser(post_cyt.userName);

            ViewBag.nameGuest = userGuest.name;
            ViewBag.lastnameGuest = userGuest.last_name;
            ViewBag.mailGuest = currentUser.Email;

            return View(post_cyt);
        }
        //
        // GET: /Post_CYT/Create
        [Authorize(Roles = "Guest_C, Guest_H, Guest_I")]
        public ActionResult Create()
        {
            ViewBag.postPending = (from m in db.Post_CYT
                                   where (m.userName == User.Identity.Name && m.idStatus == 1)
                                   select m.id).Count();

            ViewBag.idStatus = new SelectList(db.Status, "idStatus", "name");
            return View();
        } 

        //
        // POST: /Post_CYT/Create

        [Authorize(Roles = "Guest_C, Guest_H, Guest_I")]
        [HttpPost]
        public ActionResult Create(Post_CYT post_cyt)
        {
            if (ModelState.IsValid)
            {        
                post_cyt.userName = User.Identity.Name;
                post_cyt.dateGuest = DateTime.Now.Date;
                post_cyt.idStatus = 1;

                db.Post_CYT.Add(post_cyt);
                db.SaveChanges();

                /***********************************************************************************************/
                /******************************* ENVÍO DE CORREO DE NOTIFICACIÓN *******************************/
                /***********************************************************************************************/
                User_I userPost = db.User_I.Find(User.Identity.Name);
                var n_ticket = (from m in db.Post_CYT
                               where m.userName == User.Identity.Name && m.idStatus == 1
                               orderby m.id descending
                               select m.id).FirstOrDefault();

                var turno = db.Turno.Find(userPost.idTurno).name;
                var sede = db.Sede.Find(userPost.idSede).name;
                var to = db.Mail.Find(1).name;
                var bodySendCorreo = "Estimado ADMINISTRADOR: <br /> <br />SE REQUIERE LA PRONTA RESPUESTA DE LA PREGUNTA correspondiente al estudiante " +
                                     "<font style='text-transform: uppercase;'>" + userPost.name + " " + userPost.last_name + "</font>" +
                                     " de N° de C.I.: V-" + userPost.UserName + " perteneciente al Turno <font style='text-transform: uppercase;'>" + turno +
                                     "</font> en la sede <font style='text-transform: uppercase;'>" + sede + "</font>.";
                var subjectSend = "CYT Ticket Soporte N° "+ n_ticket +" de " + userPost.UserName + ".";
                var msn = "";

                //Envio de correo
                var result = sendEmail(to, subjectSend, bodySendCorreo, true);
                if (result)
                {
                    msn = "Correo de Ticket de Soporte enviado Correctamente";
                }
                else
                {
                    msn = "No se pudo enviar el Correo de Ticket de Soporte debido a problemas con el servidor";
                }

                /***********************************************************************************************/
                /***********************************************************************************************/

                return RedirectToAction("SearchIndexG", new { msn = msn });  
            }

            ViewBag.idStatus = new SelectList(db.Status, "idStatus", "name", post_cyt.idStatus);
            return View(post_cyt);
        }
        
        //
        // GET: /Post_CYT/Edit/5
        [Authorize(Roles = "Admin")]
        public ActionResult Edit(int id)
        {
            Post_CYT post_cyt = db.Post_CYT.Find(id);
            return View(post_cyt);
        }

        //
        // POST: /Post_CYT/Edit/5
        [Authorize(Roles = "Admin")]
        [HttpPost]
        public ActionResult Edit(int id, string textoAdmin)
        {
            Post_CYT post_CYT = db.Post_CYT.Find(id);
            post_CYT.textoAdmin = textoAdmin;
            post_CYT.userAdmin = User.Identity.Name;
            post_CYT.dateAdmin = DateTime.Now.Date;
            post_CYT.idStatus = 2;

            db.Entry(post_CYT).State = EntityState.Modified;
            db.SaveChanges();

            /***********************************************************************************************/
            /******************************* ENVÍO DE CORREO DE NOTIFICACIÓN *******************************/
            /***********************************************************************************************/
            MembershipUser currentUser = Membership.GetUser(post_CYT.userName);
            User_I userPost = db.User_I.Find(post_CYT.userName);

            var n_ticket = id;
            var to = currentUser.Email;
            var bodySendCorreo = "Estimad@ <font style='text-transform: uppercase;'>" + userPost.name + " " + userPost.last_name + "</font>:" +
                                 "<br /> <br />En relación a su PREGUNTA: "+ post_CYT.textoGuest +
                                 ".<br /> <br/> Le informamos que: " +
                                 post_CYT.textoAdmin + ".";
             var subjectSend = "CYT Respuesta Ticket Soporte N° " + n_ticket + " de " + userPost.UserName + ".";
             var msn = "";

             //Envio de correo
             var result = sendEmail(to, subjectSend, bodySendCorreo, true);
            if (result)
            {
                msn = "Correo de Respuesta de Ticket de Soporte enviado Correctamente";
            }
            else
            {
                msn = "No se pudo enviar el Correo de Respuesta de Ticket de Soporte debido a problemas con el servidor";
            }

             /***********************************************************************************************/
            /***********************************************************************************************/

            return RedirectToAction("SearchIndexA", new { msn = msn });  
        }

        //
        // GET: /Post_CYT/Delete/5
        [Authorize(Roles = "Admin")]
        public ActionResult Delete(int id)
        {
            Post_CYT post_cyt = db.Post_CYT.Find(id);
            return View(post_cyt);
        }

        //
        // POST: /Post_CYT/Delete/5
        [Authorize(Roles = "Admin")]
        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {            
            Post_CYT post_cyt = db.Post_CYT.Find(id);
            db.Post_CYT.Remove(post_cyt);
            db.SaveChanges();
            return RedirectToAction("SearchIndexA");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

        //***********************************************************************************//
        // Autor:  										                     				*//
        //***********************************************************************************//
        // sendEmail()																		*//
        // Función que se encarga de enviar los correos del sistema							*//														 			
        // _________________________________________________________________________________*//
        // Entrada: 																		*//
        // •	cc: Lista de correso separados por , a los cuales se desea enviar el mensaje*//
        // •	subject: subject que se va a enviar con el correo							*//	
        // •	body: cuerpo que se va a enviar con el correo								*//	
        // •	isBodyHtml: cboleano que dice si el cuerpo del correo es en formatao HTML	*//		
        // _________________________________________________________________________________*//
        // Salida:  Devuelve el envio de correo.											*//
        // _________________________________________________________________________________*//
        public bool sendEmail(string cc, string subject, string body, bool isBodyHtml)
        {
            var result = true;
            //Creación del objeto para enviar correo electronicos
            var mailMessage = new System.Net.Mail.MailMessage();

            string header = "Saludos, <br /><br />EL CURSO PRE-UNIVERSITARIO CRECE Y TRIUNFA INFORMA: <br /><br />";
            //Colocando el destinatario del correo
            mailMessage.To.Add(cc);
            //Estableciendo que el cuerpo del correo es en el formato Html
            mailMessage.IsBodyHtml = isBodyHtml;
            //Título del correo
            mailMessage.Subject = subject;
            //Mensaje del correo
            //Colocando el remitente del correo
            mailMessage.From = new MailAddress("postmaster@creceytriunfa.com");

            // --------------------- op 1 -------------- //
            string footer = "<br /><br />Crece Y Triunfa<br /> <br />Se inteligente... ¡Aprovecha el Tiempo!<br /><br /><br /><div style=\"font-size:14px\" >Este mensaje fue enviado automáticamente por el sistema CYT. RIF: J-40135444-0<br /><hr /><br />" +
                          "<table style=\"font-size:14px\" border=\"0\">" +
                            "<tr>" +
                                "<td>Jessica Pernía</td>" +
                                "<td>Jonás Gonzales</td>" +
                                "<td>Rayan Arroyo</td>" +
                                "</tr>" +
                                "<tr>" +
                                "<td>+58(416)4211556</td>" +
                                "<td>+58(412)2928347</td>" +
                                "<td>+58(414)1534241</td>" +
                            "</tr>" +
                          "</table><br /></div>" +
                          "<img src=\"@@IMAGE@@\" alt=\"\">";


            //string attachmentPath =  @"\comprometidosconmonaca.png";
            string path = Server.MapPath(@"~\Content\images\LogotipoSinRIF.png");

            //generate the contentID string using the datetime
            string contentID = Path.GetFileName(path).Replace(".", "") + "@zofm";

            //create the INLINE attachment<
            Attachment inline = new Attachment(path);
            inline.ContentDisposition.Inline = true;
            inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
            inline.ContentId = contentID;
            inline.ContentType.MediaType = "image/png";
            inline.ContentType.Name = Path.GetFileName(path);
            mailMessage.Attachments.Add(inline);

            // replace the tag with the correct content ID
            footer = footer.Replace("@@IMAGE@@", "cid:" + contentID);
            mailMessage.Body = header + body + footer;
            try
            {
                //Envio del correo.
                SmtpClient mailSender = new SmtpClient("mail.creceytriunfa.com"); //use this if you are in the development server
                NetworkCredential Credentials = new NetworkCredential("postmaster@creceytriunfa.com", "Asp18745490!");
                mailSender.Credentials = Credentials;
                mailSender.Send(mailMessage);
            }
            catch (Exception ex)
            {
                Response.Write("Could not send the e-mail - error: " + ex.Message);
                result = false;
            }
            return (result);
        }
    }
}